import 'package:dio/dio.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
// import 'package:flutter_video_compress/flutter_video_compress.dart';
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
// import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:package_info/package_info.dart';
import 'package:toast/toast.dart';
// import 'package:video_compress/video_compress.dart';

import 'dart:io';
import 'loading_page.dart';

import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

var dio = new Dio();

class Method {
  static final String get = "GET";
  static final String post = "POST";
  static final String put = "PUT";
  static final String head = "HEAD";
  static final String delete = "DELETE";
  static final String patch = "PATCH";
}

class HttpHelper {
//  BuildContext context =this.context;
//  LoadingPage loadingPage = LoadingPage(context);
  // static const String host = 'http://ylz.9ok6.com'; //服务器
  static const String host = 'http://app.chemogu1688.com'; //服务器
  static const String baseUrl = host + '/app/cmg_api.php?i=16&r=cmgapi.'; //请求路径

  //API 列表
  static const String API_Reg = "regInspector"; //注册检测师
  static const String API_SendCode = "sendMsg"; //发送验证码
  static const String API_UserLog = "loginInspector"; //检测师登录
  static const String API_ResetPwd = "member/resetPassword"; //普通用户充值密码
  static const String API_FeeLog = "staff/login"; //收费员登录
  static const String API_FeeResetPwd = "staff/resetPassword"; //收费员忘记密码
  static const String API_AddCar = "car/addCar";
  static const String API_DeleCar = "car/delCar";
  static const String API_CarList = "car/carList";
  static const String API_AddOrder = "order/addOrder";
  static const String API_FeeOrderList = "order/staffOrderList"; //收费员收费记录
  static const String API_UserOrderList = "getMyOrder"; //检测师订单列表
  static const String API_OrderDetail = "getOrderDetail";
  static const String API_UpLoadFile = "uploadPic";
  static const String API_UploadVideo = "uploadVideo"; //上传视频
  static const String API_AddressList = "staff/addressList";
  static const String API_payCode = "order/payQrcode";
  static const String API_OrderStatus = "order/orderStatus";
  static const String API_OrderPayStatus = "order/orderPayStatus";
  static const String API_CardList = "card/cardType"; //会员卡列表
  static const String API_MyCard = "card/applyCardList"; //我的会员卡
  static const String API_ApplyCard = "card/applyCard";
  static const String API_LevelNopay = "order/taoPiao";
  static const String API_Getshuiyin = "order/orderImages";
  static const String API_Userinfo = "getUserInfo";
  static const String API_Quelist = "getQuestion";
  static const String API_UpdateAvatar = "updateAvatar";
  static const String API_UpdateOrderStart = "setIsStart"; //设置开始检测
  static const String API_LoadTestItem = "getTestItems"; //加载检测项
  static const String API_SubOrder = "subOrder"; //提交检测项数据
  static const String API_SaveResult = "saveresult"; //保存结果
  static const String API_DrawList = "getWithDrawList"; //提现记录
  static const String API_SubDrawApply = "submitWithDraw"; //提交提现申请
  static const String API_MyMoney = "getBalance"; //我的余额
  static const String API_Qrcode = "getQRCode"; //获取我的二维码
  static const String API_QudaoCode = "getpartnerQrCode"; //获取车商经纪人的渠道二维码
  static const String API_GetScore = "getScore"; //考试记录
  static const String API_GetExam = "goexam"; //考试题目
  static const String API_SubexamAns = "answer_question"; //考试题目
  static const String API_FinishExam = "finishexam";
  static const String API_ApplyTest = "applyTest"; //申请补考
  static const String API_GetAsk = "getAnswers"; //回答详情列表
  static const String API_GetAskList = "getAnswerList"; //问答列表
  static const String API_GetAskDetail = "getQuestionDetail"; //问答详情
  static const String API_SubAskAns = "subComment"; //提交问答评论
  static const String API_SubAsk = "subAsk"; //发布问题
  static const String API_Dianzan = "dianzan"; //点赞问答
  static const String API_RegBussiness = "regBussiness"; //注册车商
  static const String API_LoginBusiness = "loginBusiness"; //车商登录
  static const String API_BusinessInfo = "businessinfo"; //车商个人信息
  static const String API_BussinessSuborder = "bussinessSuborder"; //车商 下检测订单
  static const String API_BussinessOrderDetail = "businessOrderDetail"; //车商订单详情
  static const String API_BussinessOrderList = "bussinessOrderList_v"; //车商订单列表
  static const String ApI_CarList = "carlist"; //车源列表
  static const String API_Brand = "getCarBrand"; //车辆品牌
  static const String API_CarType = "getcartype"; //车型
  static const String API_Guratee = "create_order"; //车商提交保修订单
  static const String API_SubOrderComnet = "comentorder"; //车商提交保修订单评加
//agreement
  static const String API_Agreement = "agreement"; //入驻协议

  static const String API_CancelTest = "reteststate"; //取消考试

  static const String API_GetInsurance = "getInsurance"; //获取保险公司数据

  static const String API_GetIncome = "getincome"; //获取收益
  static const String API_GetDraw = "getdrawhis"; //提现记录
  static const String API_GetDraw_V2 = "getdrawhisv2"; //提现记录新街口
  static const String API_IncomeList = "incomelist"; //收益明细
  static const String API_Version = "remoteversion";

  static const String API_UptBussinessOrder = "uptBussinessOrder"; //支付打印
  static const String API_Confirmorder = "confirmorder"; //检测师确认订单
  static const String API_pay = "paygurateefee";
  static const String API_Charger = "charger"; //充值
  //chargergroup
  static const String API_ChargerGroup = "chargergroup"; //充值认证套餐
  static const String API_Car_typeList = 'gettype_list'; //获取车型款式
  static const String API_ResetPass = "resetpassword"; //重置密码
  static const String API_ExamRecordinfo = "gettestrecord"; //考试记录的详情
  static const String API_CheckQues = "getrecquestion"; //查看考试错题
  static const String API_Order = "order/getorder";

  static const String API_BussinessFee = "getbussinessfee"; //检测费用信息
  static const String API_UptOrderEdit = "editOrder"; //更新检测报告可编辑状态
  static const String API_ChangeByte = "getbytes";
  static const String API_RefreshCar = "refreshcar"; //刷新车源
  static const String API_OrderCaogao = "bussinessorderedits"; //车商车源草稿内容
  static const String API_Changeprice = "changeprice"; //检测师更改订单价格
  static const String API_CancelPrice = "cancelchangeprice";
  static const String API_Charger_vip = "charger_vip"; //充值vip
  static const String API_ChangeCarStatus = "changecarstatus"; //更改车源状态
  static const String API_GetWxInfo = "getAppWxUser"; //code交换微信openid
  static const String API_ApplyTx = "applytx"; //申请提现新街口
  static const String API_WithdrawAcontInfo = "withdraw_info"; //获取提现账户的历史信息
  static const String API_GetTroubleCode = "gettroublecode"; //获取故障描述
  static const String API_StudyInfo = "studyinfo"; //获取学习资料
  static const String API_SubObdData = "subInsurance"; //上传保修检测obd数据
  static const String API_ConfirmSign = "confirmsign"; //检测师确认合同签字
  static const String API_GetTask = "gettask"; //获取任务列表
  static const String API_TaskDetail = "taskdetail"; //任务详情
  static const String API_ReqTask = "requsttask"; //领取任务
  static const String API_MyTask = "mytask"; //我的任务
  static const String API_QiniuToken = "getqiniutoken";
  static const String API_UptTask = "upttask";
  static const String API_TaskIncome = "taskincome"; //任务收益
  static const String API_ApplyTaskwithdraw = "applytasktx"; //申请任务收益提现
  static const String API_TaskWithdrawhis = "gettaskdrawhis"; //任务收益提现记录
  static const String API_TaskIncomeList = "taskincomelist"; //任务收益明细
  static const String API_TaskVideos = "gettaskvideos";
  static const String API_UptVideos = "uptvideo"; //更新视频上传信息
  static const String API_TaskOrders = "taskunionorder"; //任务需要关联的订单
  static const String API_DeleteVideos = "deletevideos"; //删除视频
  static const String API_Qrcodever = "getQRCodever"; //获取检测师二维码新接口
  static const String API_Post_UUID = "saveuuid";
  static const String API_Message = "messageinfo"; //消息列表

  static const String API_Chargegroupdata = "chargergroupdata"; //获取充值套餐数据
  static const String API_Bussinessgrupdata = "getbussinessgroup"; //获取商户的认证套餐信息
  static const String API_Bussinessgrouprec =
      "bussinesschargerdata"; //车商的认证充值记录
  static const String API_Create_auth_Order = "createauthorder_v"; //车商创建认证检测订单
  static const String API_Auth_record = "authorderrec"; //车商认证检测订单
  static const String API_Create_auth_by_car =
      "createauthorderbycar_v"; //车商通过车源下单
  static const String API_Sign_inline = "dosigninline"; //检测师线上签约
  static const String API_Cancel_auth_Order = "cancelauthorder"; //车商取消订单
  static const String API_Area_data = "getareadata"; //获取城市数据
  static const String API_Scanxsz = "shibiecar";
  static const String API_queryprolem = "querycarprolem"; //查询车辆数据
  static const String API_CarByPlatnum = "carbyplatnum"; //根据车牌查找是否有车源
  static const String API_Getwxpaycode = "createweixinpaycode";
  static const String API_QueryHistoryinfo = "queryhistort"; //查询记录的详细信息
  static const String API_Querybussiness = "querybussiness"; //查询商家
  static const String API_UpEnsurancecar = "uploadensuranceinfo"; //上传质保车辆信息
  static const String API_EnsuranceCarlist = "ensurancecarlist"; //质保订单列表
  static const String API_Submitensuranceinfo =
      "submitensuranceinfo"; //提交质保OBD结果
  static const String API_Bussinessgroup = "getchargergroupdata";
  static const String API_Dobussinesscharger =
      "dobussinesscharger"; //新版本的商家充值套餐
  static const String API_Bussinessquerycarinfo =
      "querydatabybussiness"; //新版本车商查询车辆信息的接口
  static const String API_GetQueryResult = "getqueryresult";//获取查询的数据详情    
  static const String API_Gurateen_product = "guranteen_products"; //质保产品类型
  static const String API_Guranteencode = "getgurantencode";//获取保修订单客户签约二维码
  static const String API_Guranteencars = "ensurancecars";//质保车源列表
  static const String API_Bussinessbuyguranteen = "usermakecreate_order";
  static const String API_BussinessGroupUseRec = "group_use";//商家套餐使用情况
  static const String API_Querydatatype = "querydata_product";//查询数据的类型数据
  static const String API_PrecheckGroup = "precheckgroup";//预先检查用户是否能下认证检测订单
  static const String API_PrecheckBaoxiu = "precheckbaoxiu";//查看是否能保修
  static const String API_QuerydataRecord = "querydatarecord";//数据查询记录
  static const String API_Requerydata = "getweibaopengzhuangdata";//重新发起数据查询
  static const String API_PayqueryOrder = "payquerydataorder";//从订单列表支付
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods

  static void get(String url, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    if (params != null && params.isNotEmpty) {
      StringBuffer sb = new StringBuffer("?");
      params.forEach((key, value) {
        sb.write("$key" + "=" + "$value" + "&");
      });
      String paramStr = sb.toString();
      paramStr = paramStr.substring(0, paramStr.length - 1);
      url += paramStr;
    }
    try {
      http.Response res = await http.get(Uri.parse(baseUrl + url));
      if (callback != null) {
        final result = json.decode(res.body.toString());
        callback(result);
      }
    } catch (exception) {
      if (errorCallback != null) 
      {
        errorCallback(exception);
      }
    }
  }

  static void post(String url, Function callback,
      {Map<String, Object> params, Function errorCallback}) async {
    ///app/cmg_api.php?i=16&r=cmgapi.dianzan
    ///
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      String localVersions = packageInfo.version;
      params['app_ver'] = localVersions;
      http.Response res =
          await http.post(Uri.parse(baseUrl + url), body: params);
      print('请求地址:' + baseUrl + url);
      if (callback != null) {
        final result = json.decode(res.body.toString());
        callback(result);
      }
    } catch (e) {
      // if (errorCallback != null) {
      //   errorCallback(e);
      //   print(e);
      //   print('-------异常--------');
      // }
    }
  }

  static void postOtherUrl(String url, Function callback,
      {Map<String, Object> params, Function errorCallback}) async {
    ///app/cmg_api.php?i=16&r=cmgapi.dianzan

    try {
      http.Response res = await http.post(Uri.parse(url), body: params);
      print('请求地址:' + baseUrl + url);
      if (callback != null) {
        final result = json.decode(res.body.toString());

        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  static void postUrl(String url, BuildContext context, Function callback,
      {Map<String, Object> params, Function errorCallback}) async {
    print(params);
    try {
      http.Response res =
          await http.post(Uri.parse(baseUrl + url), body: params);
      print('请求地址:' + baseUrl + url);
      if (callback != null) {
        final result = json.decode(res.body.toString());
        callback(result);
      }
    } catch (e) {
      Toast.show('网络异常，请重试！', context);
      //Toast.show(e.message, context);
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  //转换百度地图位置信息
  static void PostLocation(Function callback,
      {Map<String, String> params}) async {
    String url = '';
    if (Platform.isIOS) {
      url =
          'http://api.map.baidu.com/reverse_geocoding/v3/?ak=hHqbyRqLANLY1rL0EU5C16jfDEyRhoCp&mcode=com.chemg.chemg&output=json&coordtype=wgs84ll&location=' +
              params['lat'] +
              ',' +
              params['lng'];
    } else if (Platform.isAndroid) {
      url =
          'http://api.map.baidu.com/reverse_geocoding/v3/?ak=qphSiTiHvW77B9xzMwqIQQauI4Q6edop&mcode=7D:70:CA:CB:71:3B:B5:4D:EA:14:81:33:45:BB:33:5A:16:BF:22:2E&output=json&coordtype=wgs84ll&location=' +
              params['lat'] +
              ',' +
              params['lng'];
    }
    http.Response res = await http.get(Uri.parse(url));
    print(url);
    if (callback != null) {
      final result = json.decode(res.body.toString());
      callback(result);
    }
  }

  static void postqrCode(String url, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    try {
      http.Response res = await http.post(
          Uri.parse("https://www.kuaizhan.com/common/encode-png?large=true"),
          body: params);

      if (callback != null) {
        print('------------二维码响应结果------------');
        final result = json.decode(res.body.toString());
        print(result);
        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  static void upLoadvideo(File image, Function callback, Function progress,
      {Map<String, String> params, Function errorCallback}) async {
    try {
      String path = "";
      // if(params['isgallery']=="0"){
      // final  info = await FlutterVideoCompress().compressVideo(
      //   image.path,
      //   quality: VideoQuality.HighestQuality,
      //   deleteOrigin: false,
      // );
      // // final info = await VideoCompress.compressVideo(
      // //   image.path,
      // //   quality: VideoQuality.MediumQuality,

      // //   deleteOrigin: false, // It's false by default
      // // );
      // //File _files = await flutterVideo
      // //   image.path,
      // //   quality: 40,
      // // );

      // // String path = _files.path;
      //  //String path = _files.path.replaceAll('.jpg', '.mp4');
      //  path = info.path;

      // }else{
      // //   final info = await FlutterVideoCompress().compressVideo(
      // //   image.path,
      // //   quality: VideoQuality.HighestQuality,
      // //   deleteOrigin: false,
      // // );
      // // path = info.path;
      //   // path = image.uri.path;
      //    path = image.path;

      // }
      path = image.path;

      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
      // FormData formData = new FormData.fromMap(
      //     {"file": await MultipartFile.fromFile(path, filename: name)});
      FormData formData = new FormData.fromMap({
        "file": await MultipartFile.fromFile(path, filename: name),
        'key': params['key'],
        'token': params['token']
      });
      // FormData formData = new FormData.fromMap(
      //     {"fileBinaryData": await MultipartFile.fromFile(path, filename: name),
      //     'fileName':'video','upload_token':'U4dvcIu6g6yOl9VddJbEWvHrvZXr2qLGOuuE58hN:Y2I5MWM0ZmFkZjYyMjljN2VlOGVhZjU3MDc4OTg1OWI1Zjg0ODZjMw==:eyJzY29wZSI6InlsemRldiJ9'});
      //  var data = uploadAxios.post('', formData);
      //  print(data);

      Dio dio = new Dio();
      // var respone =
      //     await dio.post<String>('http://thinkphp5.ynczm.com/', data: formData);
      //http://static.ylz.ynczm.com/
      // var respone =
      //     await dio.post<String>(baseUrl + API_UploadVideo, data: formData);
      var respone = await dio.post<String>('https://up-z2.qiniup.com',
          data: formData, onSendProgress: (int sent, int total) {
        progress(sent, total);
      });
      print('视频上传结果');
      if (callback != null) {
        final result = json.decode(respone.toString());
        print(result);
        callback(result);
      }
    } catch (e) {
      if (errorCallback != null) {
        errorCallback(e);
        print(e);
        print('-------异常--------');
      }
    }
  }

  //上传图片封装方法
  static void upLoadImage(File image, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    // try {
    EasyLoading.show(status: "上传中...");
    File _files = await FlutterNativeImage.compressImage(
      image.path,
      quality: 70,
    );
    String path = _files.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.fromMap(
        {"file": await MultipartFile.fromFile(path, filename: name)});
    Dio dio = new Dio();
    var respone =
        await dio.post<String>(baseUrl + API_UpLoadFile, data: formData);
    print('图片上传结果');
    EasyLoading.dismiss();
    if (callback != null) {
      final result = json.decode(respone.toString());
      print(result);
      callback(result);
    }
    // }catch(e){
    //   if (errorCallback != null) {
    //     errorCallback(e);
    //     print(e);
    //     print('-------异常--------');
    //   }
  }

  static void upLoadSignImage(String image, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    // try {

    // File _files = await FlutterNativeImage.compressImage(
    //   image.path,
    //   quality: 70,
    // );
    EasyLoading.show(status: "上传中...");
    String path = image;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.fromMap(
        {"file": await MultipartFile.fromFile(path, filename: name)});

    Dio dio = new Dio();
    var respone =
        await dio.post<String>(baseUrl + API_UpLoadFile, data: formData);
    print('图片上传结果');
    EasyLoading.dismiss();
    if (callback != null) {
      final result = json.decode(respone.toString());
      print(result);
      callback(result);
    }
    // }catch(e){
    //   if (errorCallback != null) {
    //     errorCallback(e);
    //     print(e);
    //     print('-------异常--------');
    //   }
  }
  //上传图片封装方法//上传图片封装方法

  static void upLoadImageNocompress(File image, Function callback,
      {Map<String, String> params, Function errorCallback}) async {
    // try {
    EasyLoading.show(status: "上传中...");
    File _files = await FlutterNativeImage.compressImage(
      image.path,
      quality: 60,
    );
    String path = _files.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
    FormData formData = new FormData.fromMap(
        {"file": await MultipartFile.fromFile(path, filename: name)});

    Dio dio = new Dio();
    var respone =
        await dio.post<String>(baseUrl + API_UpLoadFile, data: formData);
    print('图片上传结果');
    EasyLoading.dismiss();
    if (callback != null) {
      final result = json.decode(respone.toString());
      print(result);
      callback(result);
    }
  }
}
// static Future uploadImg(imgfile) async{
//     String path = imgfile.path;
//     var name = path.substring(path.lastIndexOf("/") + 1, path.length);
//     FormData formData = new FormData.fromMap({
//       "file": new (new File(path), name)
//     });
//     Response response;
//     Dio dio =new Dio();
//     response =await dio.post(‘后端接口‘,data: formData);
//     if(response.statusCode == 200){
//       return response.data;
//     }else{
//       throw Exception(‘后端接口异常‘);
//     }
//   }

// 上传七牛云服务
class UploadAxios {
  Dio uploadDio;
  UploadAxios() {
    uploadDio = Dio(BaseOptions(
      baseUrl: 'https://up-z2.qiniup.com',
      connectTimeout: 5000000,
      receiveTimeout: 10000000,
    ));
  }

  // post
  dynamic post(String url, [dynamic params]) async {
    try {
      Response response = await uploadDio.post(url, data: params);
      return response.data;
    } catch (e) {
      return;
    }
  }

  // 并发
  Future<List<dynamic>> all(Iterable<Future> list) async {
    return await Future.wait(list);
  }
}

final UploadAxios uploadAxios = UploadAxios();
